package com.mucfc.crm.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 随机访问文件类
 *
 * @author HuQingmiao
 */
public class FileUtil {
    private static Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * @param file     目标文件
     * @param append   true:追加方式写入 false:新建文件写入
     * @param lineList
     * @throws Exception
     */
    public static void writeOut(File file, boolean append, List<String> lineList) throws Exception {
        if (lineList.isEmpty()) {
            return;
        }

        if (!append) {
            if (file.exists()) {
                file.delete();
            }
        }

        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(file, append);
            bw = new BufferedWriter(fw);

            for (String line : lineList) {
                bw.append(line);
                bw.append('\n');
                bw.flush();
            }
            bw.close();

        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            throw e;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    /**
     * @param file   目标文件
     * @param append true:追加方式写入 false:新建文件写入
     * @param str
     * @throws Exception
     */
    public static void writeOut(File file, boolean append, String str) throws Exception {
        if (str == null || "".equals(str)) {
            return;
        }

        if (!append) {
            if (file.exists()) {
                file.delete();
            }
        }

        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(file, append);
            bw = new BufferedWriter(fw);
            bw.append(str);
            bw.flush();
            bw.close();

        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            throw e;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    /**
     * @param file 目标文件
     * @throws Exception
     */
    public static List<String> readIn(File file) throws Exception {

        LinkedList<String> lineList = new LinkedList<String>();
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(file);
            br = new BufferedReader(fr);

            String line = null;
            while ((line = br.readLine()) != null) {
                lineList.add(line);
            }
            br.close();
            fr.close();

            return lineList;

        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
            throw e;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                log.error("", e);
            }
        }
    }

    public static String retrieveContent(File file) throws Exception {
        List<String> lineList = readIn(file);
        StringBuffer str = new StringBuffer();
        for (String line : lineList) {
            str.append(line);
            str.append("\n");
        }
        return str.toString();
    }


    /**
     * 获得指定文件的byte数组
     */
    public static byte[] getBytes(File file) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 根据byte数组，生成文件
     */
    public static File getFile(byte[] bfile, String absFilename) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = new File(absFilename);
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }


    public static void main(String args[]) {
        try {
//            File f = new File("d:/rpt_out/a.html");
//            String sa = FileUtil.readToStr(f);
//            log.info("2>>" + sa);

            File f1 = new File("d:/rpt_out/a.xml");
            File f2 = new File("d:/rpt_out/b.html");
            File f3 = new File("d:/rpt_out/c.html");

            File f4 = new File("d:/ddddddddddd4.txt");
            List<String> outList = new ArrayList<String>();
            outList.add("asdf");
            outList.add("中国");
            writeOut(f4, false, outList);

            List<String> inList = readIn(f4);
            for (String line : inList) {
                System.out.println(">>" + line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
